<template>
  <view class="home-page">
    <!-- 状态栏占位 -->
    <view class="status-bar"></view>

    <!-- 顶部励志语 -->
    <view class="motto-section" @click="showMottoEditor">
      <text class="motto-text">{{ homeStore.motto }}</text>
      <uni-icons type="compose" size="18" color="#666"></uni-icons>
    </view>

    <!-- 月历组件 -->
    <HomeCalendar class="calendar-section" />

    <!-- 日志列表 -->
    <scroll-view 
      class="diary-list"
      scroll-y
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="homeStore.currentDateDiaries.length === 0" class="empty-tip">
        <uni-icons type="editor" size="48" color="#eee"></uni-icons>
        <text class="tip-text">点击右下角按钮开始记录</text>
      </view>

      <EditorContent 
        v-else
        :diaries="processedDiaries"
        @edit="handleEditDiary"
        @preview-image="previewImage"
      />
    </scroll-view>

    <!-- 新建按钮 -->
    <view 
      class="float-btn" 
      @click="handleNewDiary"
      v-show="!editorVisible"
    >
      <uni-icons type="plus" size="24" color="white"></uni-icons>
    </view>

    <!-- 励志语编辑弹窗 -->
    <uni-popup ref="mottoPopup" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="编辑励志语"
        :value="homeStore.motto"
        placeholder="输入励志语（30字以内）"
        @confirm="updateMotto"
        :maxlength="30"
      />
    </uni-popup>

    <!-- 日志编辑器 -->
    <uni-popup 
      ref="editorPopup" 
      type="bottom" 
      :is-mask-click="false"
      @maskClick="handleEditorClose"
    >
      <view class="editor-wrapper">
        <RichTextEditor
          v-if="editorReady"
          :key="editorKey"
          :diary-id="currentDiaryId"
          :initial-content="editingContent"
          :initial-images="editingImages"
          :show-delete="!!currentDiaryId"
          @save="handleEditorSave"
          @delete="handleDiaryDelete"
          @cancel="handleEditorClose"
        />
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useHomeStore } from '@/stores/homeStore'
import HomeCalendar from '@/components/modules/home/HomeCalendar.vue'
import RichTextEditor from '@/components/functional/RichTextEditor.vue'
import EditorContent from '@/components/common/EditorContent.vue'

const homeStore = useHomeStore()
const mottoPopup = ref(null)
const editorPopup = ref(null)
const refreshing = ref(false)
const editorVisible = ref(false)
const editorReady = ref(false)
const editorKey = ref(0)

// 编辑状态
const currentDiaryId = ref(null)
const editingContent = ref('')
const editingImages = ref([])

// 处理后的日志数据
const processedDiaries = computed(() => {
  return homeStore.currentDateDiaries.map(d => ({
    ...d,
    images: d.images.map(img => processImagePath(img))
  }))
})

// 图片路径处理
const processImagePath = (img) => {
  return img.startsWith('_www/') ? `/static/${img}` : img
}

onMounted(async () => {
  await homeStore.initFromStorage()
})

// 显示励志语编辑
const showMottoEditor = () => {
  mottoPopup.value.open()
}

// 更新励志语
const updateMotto = (value) => {
  homeStore.updateMotto(value.trim())
}

// 处理新建日志
const handleNewDiary = async () => {
  currentDiaryId.value = null
  editingContent.value = ''
  editingImages.value = []
  await initEditor()
  editorPopup.value.open()
}

// 处理编辑日志
const handleEditDiary = async (diaryId) => {
  const diary = homeStore.currentDateDiaries.find(d => d.id === diaryId)
  if (diary) {
    currentDiaryId.value = diaryId
    editingContent.value = diary.content
    editingImages.value = [...diary.images]
    await initEditor()
    editorPopup.value.open()
  }
}

// 初始化编辑器
const initEditor = async () => {
  editorReady.value = false
  editorKey.value++
  await nextTick()
  editorVisible.value = true
  editorReady.value = true
}

// 处理编辑器保存（修复保存后关闭问题）
const handleEditorSave = async ({ content, images }) => {
  try {
    if (currentDiaryId.value) {
      await homeStore.saveDiary(content, images, currentDiaryId.value)
    } else {
      await homeStore.saveDiary(content, images)
    }
    // 保存成功后立即关闭编辑器
    handleEditorClose()
    // 刷新当前日期数据
    await homeStore.initFromStorage()
  } catch (error) {
    uni.showToast({ title: '保存失败，请重试', icon: 'none' })
  } finally {
    editorVisible.value = false
  }
}

// 处理日志删除
const handleDiaryDelete = async (diaryId) => {
  await homeStore.deleteDiary(diaryId)
  handleEditorClose()
  await homeStore.initFromStorage()
}

// 关闭编辑器（修复关闭逻辑）
const handleEditorClose = async () => {
  editorPopup.value.close()
  editorVisible.value = false
  editorReady.value = false
  await nextTick()
  // 重置编辑状态
  currentDiaryId.value = null
  editingContent.value = ''
  editingImages.value = []
}

// 图片预览
const previewImage = ({ index }) => {
  const urls = processedDiaries.value
    .flatMap(d => d.images)
    .map(img => img.src)
  uni.previewImage({
    current: urls[index],
    urls
  })
}

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true
  try {
    await homeStore.initFromStorage()
  } finally {
    refreshing.value = false
  }
}
</script>

<style scoped lang="scss">
.home-page {
  height: 100vh;
  background: #f5fbfe;
}

.status-bar {
  height: var(--status-bar-height);
}

.motto-section {
  padding: 16px;
  margin: 12px 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(135, 206, 235, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;

  .motto-text {
    color: #2775b6;
    font-size: 16px;
    margin-right: 8px;
    line-height: 1.4;
  }
}

.calendar-section {
  margin: 0 16px;
}

.diary-list {
  flex: 1;
  padding: 0 8px;
  margin-top: 12px;
}

.empty-tip {
  padding: 60px 0;
  text-align: center;

  .tip-text {
    color: #ccc;
    font-size: 14px;
    margin-top: 12px;
  }
}

.float-btn {
  position: fixed;
  right: 24px;
  bottom: calc(24px + env(safe-area-inset-bottom));
  width: 56px;
  height: 56px;
  background: #87CEEB;
  border-radius: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(135, 206, 235, 0.3);
  transition: transform 0.2s;

  &:active {
    transform: scale(0.95);
  }
}

.editor-wrapper {
  background: white;
  border-radius: 16px 16px 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}
</style>